import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:vischat/core/annotations/getx_route_enhanced.dart';
import 'package:vischat/core/utils/custom_date_utils.dart';
import 'package:vischat/generated/icons/app_icons.dart';
import 'package:vischat/modules/media/media_picker_binding.dart';
import 'package:vischat/modules/media/media_picker_controller.dart';
import 'package:vischat/shared/widgets/buttons/custom_button.dart';

@GetXRoute('/media_picker', binding: MediaPickerBinding)
class MediaPickerPage extends GetView<MediaPickerController> {
  const MediaPickerPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Obx(() => Text(controller.currentAlbum)),
        actions: [
          IconButton(
            icon: Icon(AppIcons.arrow_down),
            onPressed: () => _showAlbumSelection(),
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading) {
          return Center(child: CircularProgressIndicator());
        }
        return _buildMediaGrid(controller);
      }),
      bottomNavigationBar: Obx(() => _buildBottomBar(controller)),
    );
  }

  Widget _buildMediaGrid(MediaPickerController controller) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 2.w,
        mainAxisSpacing: 2.w,
      ),
      itemCount: controller.allMedia.length,
      itemBuilder: (context, index) {
        final asset = controller.allMedia[index];
        return _buildMediaItem(controller, asset);
      },
    );
  }

  Widget _buildMediaItem(MediaPickerController controller, AssetEntity asset) {
    return FutureBuilder<File?>(
      future: controller.getThumbnail(asset),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return Container(color: Colors.grey[300]);
        }
        return GestureDetector(
          onTap: () => controller.previewMedia(asset),
          child: Stack(
            fit: StackFit.expand,
            children: [
              Image.file(snapshot.data!, fit: BoxFit.cover),
              if (asset.type == AssetType.video)
                Positioned(
                  right: 10.w,
                  bottom: 10.h,
                  child: Text(
                    CustomDateUtils.formatDuration(asset.duration),
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              Positioned(
                right: 0.w,
                top: 0.h,
                child: Obx(
                  () => Checkbox(
                    value: controller.selectedMedia.contains(asset),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(20.r),
                    ),
                    checkColor: Colors.white,
                    activeColor: Colors.blue,
                    side: WidgetStateBorderSide.resolveWith(
                      (state) => const BorderSide(color: Colors.lightBlue),
                    ),
                    visualDensity: VisualDensity.compact,
                    onChanged:
                        (val) => controller.selectAsset(val ?? false, asset),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildBottomBar(MediaPickerController controller) {
    return Container(
      height: 80.h,
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'assets.selected'.trParams({
              'count': '${controller.selectedMedia.length}',
            }),
          ),
          CustomButton(
            height: 54.h,
            width: 160.w,
            text: 'button.complete'.tr,
            disable: controller.selectedMedia.isEmpty,
            onTap: () => Get.back(result: controller.selectedMedia),
          ),
        ],
      ),
    );
  }

  void _showAlbumSelection() {
    showModalBottomSheet(
      context: Get.context!,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder: (context) {
        return Obx(
          () => ListView.builder(
            itemCount: controller.albums.length,
            itemBuilder: (context, index) {
              final album = controller.albums[index];
              return FutureBuilder<int>(
                future: album.assetCountAsync,
                builder: (context, snapshot) {
                  final count =
                      snapshot.hasData ? snapshot.data.toString() : '...';
                  return ListTile(
                    title: Text(album.name),
                    trailing: Text(count),
                    onTap: () {
                      controller.switchAlbum(album);
                      Get.back();
                    },
                  );
                },
              );
            },
          ),
        );
      },
    );
  }
}
